home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / gnu / gptx-0_2.lha / gptx-0.2 / gptx.c < prev    next >
C/C++ Source or Header  |  1991-10-10  |  62KB  |  2,227 lines

  1. /* Permuted index, with keywords in their context.
  2.    Copyright (C) 1990 Free Software Foundation, Inc.
  3.    Francois Pinard <pinard@iro.umontreal.ca>, 1988.
  4.  
  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 1, or (at your option)
  8.    any later version.
  9.  
  10.    This program is distributed in the hope that it will be useful, but
  11.    WITHOUT ANY WARRANTY; without even the implied warranty of
  12.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13.    General Public License for more details.
  14.  
  15.    You should have received a copy of the GNU General Public License
  16.    along with this program; if not, write to the Free Software
  17.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  18. */
  19.  
  20.  
  21. /* AIX requires the alloca decl to be the first thing in the file. */
  22. #ifdef __GNUC__
  23. #define alloca __builtin_alloca
  24. #else
  25. #ifdef sparc
  26. #include <alloca.h>
  27. #else
  28. #ifdef _AIX
  29.  #pragma alloca
  30. #else
  31. char *alloca ();
  32. #endif
  33. #endif
  34. #endif
  35.  
  36.  
  37. /* Global defines.  */
  38.  
  39. /* Reallocation step when swallowing non regular files.  The value is not
  40.    the actual reallocation step, but its base two logarithm.  */
  41. #define SWALLOW_REALLOC_LOG 12
  42.  
  43. /* Define to be the same as in "regex.c".  */
  44. #define Sword 1
  45.  
  46. /* The following specifies the getopt string to use.  */
  47.  
  48. #ifdef PTX_COMPATIBILITY
  49. #define GETOPT_STRING "b:i:fg:o:trw:C"
  50. #else
  51. #define GETOPT_STRING "b:i:fg:o:trw:ACF:ORS:TW:"
  52. #endif
  53.  
  54.  
  55. /* Include files.  */
  56.  
  57. #include <stdio.h>
  58. #include <fcntl.h>
  59. #include <sys/types.h>
  60. #include <sys/stat.h>
  61. #ifndef __STDC__
  62. int fstat ();
  63. #else
  64. int fstat (int, struct stat *);
  65. #endif
  66.  
  67. #ifdef USG
  68. #include <string.h>
  69. #else /* not USG */
  70. #include <strings.h>
  71. #define strchr index
  72. #define strrchr rindex
  73. #endif /* not USG */
  74. #include <getopt.h>
  75.  
  76. #include "bumpalloc.h"
  77. #include "ctype.h"
  78. #include "gptx.h"
  79. #include "regex.h"
  80.  
  81.  
  82. /* Global definitions.  */
  83.  
  84.  
  85. /* Some types.  */
  86.  
  87. enum Format
  88. {
  89.   UNKNOWN_FORMAT,        /* output format still unknown */
  90.   DUMB_FORMAT,            /* output for a dumb terminal */
  91.   ROFF_FORMAT,            /* output for `troff' or `nroff' */
  92.   TEX_FORMAT,            /* output for `TeX' or `LaTeX' */
  93. };
  94.  
  95. typedef short DELTA;        /* to hold displacement within one context */
  96.  
  97.  
  98. /* Program name.  */
  99.  
  100. const char *program_name;    /* name of this program */
  101.  
  102.  
  103. /* Program options.  */
  104.  
  105. int auto_reference = 0;        /* references are `file_name(line_number)' */
  106. int input_reference = 0;    /* references at beginning of input lines */
  107. int right_reference = 0;    /* output references after right context  */
  108. int line_width = 72;        /* output line width in characters */
  109. int gap_size = 3;        /* number of spaces between output fields */
  110. const char *truncation_string = "/"; /* string used to mark line truncations */
  111. enum Format output_format = UNKNOWN_FORMAT; /* output format */
  112.  
  113. int fold_lower_to_upper = 0;    /* fold upper and lower case for sorting */
  114. const char *context_regex_string = NULL; /* raw regex for end of context */
  115. const char *word_regex_string = NULL; /* raw regex for a keyword */
  116. const char *break_file = NULL;    /* name of the `Break characters' file */
  117. const char *only_file = NULL;    /* name of the `Only words' file */
  118. const char *ignore_file = NULL;    /* name of the `Ignore words' file */
  119.  
  120.  
  121. /* A BLOCK delimit a region in memory of arbitrary size, like the copy of a
  122.    whole file.  A WORD is something smaller, its length should fit in a
  123.    short integer.  A WORD_TABLE may contain several WORDs.  */
  124.  
  125. typedef struct
  126.   {
  127.     char *start;        /* pointer to beginning of region */
  128.     char *end;            /* pointer to end + 1 of region */
  129.   }
  130. BLOCK;
  131.  
  132. typedef struct
  133.   {
  134.     char *start;        /* pointer to beginning of region */
  135.     short size;            /* length of the region */
  136.   }
  137. WORD;
  138.  
  139. typedef struct
  140.   {
  141.     WORD *start;        /* array of WORDs */
  142.     int length;            /* number of entries */
  143.   }
  144. WORD_TABLE;
  145.  
  146.  
  147. /* Pattern description tables.  */
  148.  
  149. /* For each character, provide its folded equivalent.  */
  150. unsigned char folded_chars[1 << BYTEWIDTH];
  151.  
  152. /* For each character, indicate if it is part of a word.  */
  153. char syntax_table[1 << BYTEWIDTH];
  154.  
  155. /* Compiled regex for end of context.  */
  156. struct re_pattern_buffer *context_regex;
  157.  
  158. /* End of context pattern register indices.  */
  159. struct re_registers context_regs;
  160.  
  161. /* Compiled regex for a keyword.  */
  162. struct re_pattern_buffer *word_regex;
  163.  
  164. /* Keyword pattern register indices.  */
  165. struct re_registers word_regs;
  166.  
  167. /* A word characters fastmap is used only when no word regexp has been
  168.    provided.  A word is then made up of a sequence of one or more characters
  169.    allowed by the fastmap.  Contains !0 if character allowed in word.  Not
  170.    only this is faster in most cases, but it simplifies the implementation
  171.    of the Break files.  */
  172. char word_fastmap[1 << BYTEWIDTH];
  173.  
  174. /* Maximum length of any word read.  */
  175. int maximum_word_length;
  176.  
  177. /* Maximum width of any reference used.  */
  178. int reference_max_width;
  179.  
  180.  
  181. /* Ignore and Only word tables.  */
  182.  
  183. WORD_TABLE ignore_table;    /* table of words to ignore */
  184. WORD_TABLE only_table;        /* table of words to select */
  185.  
  186. #define ALLOC_NEW_WORD(table) \
  187.   BUMP_ALLOC ((table)->start, (table)->length, 8, WORD)
  188.  
  189.  
  190. /* Source text table, and scanning macros.  */
  191.  
  192. int number_input_files;        /* number of text input files */
  193. int total_line_count;        /* total number of lines seen so far */
  194. const char **input_file_name;    /* array of text input file names */
  195. int *file_line_count;        /* array of `total_line_count' values at end */
  196.  
  197. BLOCK text_buffer;        /* file to study */
  198. char *text_buffer_maxend;    /* allocated end of text_buffer */
  199.  
  200. /* SKIP_NON_WHITE used only for getting or skipping the reference.  */
  201.  
  202. #define SKIP_NON_WHITE(cursor, limit)                    \
  203.   while (cursor < limit && !isspace(*cursor))                \
  204.     cursor++
  205.  
  206. #define SKIP_WHITE(cursor, limit)                    \
  207.   while (cursor < limit && isspace(*cursor))                \
  208.     cursor++
  209.  
  210. #define SKIP_WHITE_BACKWARDS(cursor, start)                \
  211.   while (cursor > start && isspace(cursor[-1]))                \
  212.     cursor--
  213.  
  214. #define SKIP_SOMETHING(cursor, limit)                    \
  215.   do                                    \
  216.     if (word_regex_string)                        \
  217.       {                                    \
  218.     int count;                            \
  219.     count = re_match (word_regex, cursor, limit - cursor, 0, NULL);    \
  220.     cursor += count <= 0 ? 1 : count;                \
  221.       }                                    \
  222.     else if (word_fastmap[(unsigned char) *cursor])            \
  223.       while (cursor < limit && word_fastmap[(unsigned char) *cursor])    \
  224.     cursor++;                            \
  225.     else                                \
  226.       cursor++;                                \
  227.   while (0)
  228.  
  229.  
  230. /* Occurrences table.
  231.  
  232.    The `keyword' pointer provides the central word, which is surrounded by a
  233.    left context and a right context.  The `keyword' and `length' field allow
  234.    full 8-bit characters keys, even including NULs.  At other places in this
  235.    program, the name `keyafter' refers to the keyword followed by its right
  236.    context.
  237.  
  238.    The left context does not extend, towards the beginning of the file,
  239.    further than a distance given by the `left' value.  This value is
  240.    relative to the keyword beginning, it is usually negative.  This insures
  241.    that, except for white space, we will never have to backward scan the
  242.    source text, when it is time to generate the final output lines.
  243.  
  244.    The right context, indirectly attainable through the keyword end, does
  245.    not extend, towards the end of the file, further than a distance given by
  246.    the `right' value.  This value is relative to the keyword beginnin, it is
  247.    usually positive.
  248.  
  249.    When automatic references are used, the `reference' value is the overall
  250.    line number in all input files read so far, in this case, it is of type
  251.    (int).  When input references are used, the `reference' value indicates
  252.    the distance between the keyword beginning and the start of the reference
  253.    field, it is of type (DELTA) and usually negative.  Also, to save space,
  254.    the `reference' field is used only if automatic references are used or if
  255.    the source text have references, otherwize it is not even allocated.  The
  256.    variable sizeof_occurs contains the actual size of each OCCURS for this
  257.    run, taking care of the variable size of the `reference' value.
  258.  
  259.    PLEASE NOTE that, for this reason, the reference field should be kept
  260.    last in the structure.  */
  261.  
  262. typedef struct
  263.   {
  264.     WORD key;            /* description of the keyword */
  265.     DELTA left;            /* distance to left context start */
  266.     DELTA right;        /* distance to right context end */
  267.     int reference;        /* reference descriptor */
  268.   }
  269. OCCURS;
  270.  
  271. /* The various OCCURS tables are indexed by the language.  But the time
  272.    being, there is no such multiple language support.  */
  273.  
  274. OCCURS *occurs_table[1];    /* all words retained from the read text */
  275. int number_of_occurs[1];    /* number of used slots in occurs_table */
  276. int sizeof_occurs;        /* size of each allocated OCCURS */
  277.  
  278. #define ALLOC_NEW_OCCURS(language)                    \
  279.   BUMP_ALLOC_VARSIZE                            \
  280.     (occurs_table[language], number_of_occurs[language],        \
  281.      9, OCCURS, sizeof_occurs)
  282.  
  283.  
  284. /* Communication among output routines.  */
  285.  
  286. /* Indicate if special output processing is requested for each character.  */
  287. char edited_flag[1 << BYTEWIDTH];
  288.  
  289. int half_line_width;        /* half of line width, reference excluded */
  290. int before_max_width;        /* maximum width of before field */
  291. int keyafter_max_width;        /* maximum width of keyword-and-after field */
  292. int truncation_string_length;    /* length of string used to flag truncation */
  293.  
  294. /* When context is limited by lines, wraparound may happen on final output:
  295.    the `head' pointer gives access to some supplementary left context which
  296.    will be seen at the end of the output line, the `tail' pointer gives
  297.    access to some supplementary right context which will be seen at the
  298.    beginning of the output line. */
  299.  
  300. BLOCK tail;            /* tail field */
  301. int tail_truncation;        /* flag truncation after the tail field */
  302.  
  303. BLOCK before;            /* before field */
  304. int before_truncation;        /* flag truncation before the before field */
  305.  
  306. BLOCK keyafter;            /* keyword-and-after field */
  307. int keyafter_truncation;    /* flag truncation after the keyafter field */
  308.  
  309. BLOCK head;            /* head field */
  310. int head_truncation;        /* flag truncation before the head field */
  311.  
  312. BLOCK reference;        /* reference field for input reference mode */
  313.  
  314.  
  315. /* Miscellaneous routines.  */
  316.  
  317.  
  318. /* Diagnose an input/output error for FILE_NAME, then exit with non-zero
  319.    status.  The perror message will be prefixed by the program name.  */
  320.  
  321. #ifndef __GNUC__
  322. void
  323. #else
  324. void volatile
  325. #endif
  326. #ifndef __STDC__
  327. perror_and_exit (file_name)
  328.      char *file_name;
  329. #else
  330. perror_and_exit (const char *file_name)
  331. #endif
  332. {
  333.   fprintf (stderr, "%s: ", program_name);
  334.   perror (file_name);
  335.   exit (1);
  336. }
  337.  
  338.  
  339. /* Compile the regex represented by STRING, diagnose and abort if any error.
  340.    Returns the compiled regex structure.  */
  341.  
  342. struct re_pattern_buffer *
  343. #ifndef __STDC__
  344. alloc_and_compile_regex (string)
  345.      char *string;
  346. #else
  347. alloc_and_compile_regex (const char *string)
  348. #endif
  349. {
  350.   struct re_pattern_buffer *pattern; /* newly allocated structure */
  351.   char *message;        /* error message returned by regex.c */
  352.  
  353.   pattern = (struct re_pattern_buffer *)
  354.     xmalloc (sizeof (struct re_pattern_buffer));
  355.  
  356.   pattern->buffer = NULL;
  357.   pattern->allocated = 0;
  358.   pattern->translate = fold_lower_to_upper ? (char *) folded_chars : NULL;
  359.   pattern->fastmap = (char *) xmalloc (1 << BYTEWIDTH);
  360.  
  361.   /* Note: regex.h and regex.c do not declare const parameters, so the
  362.      following call generates a spurious: `warning: argument passing of
  363.      non-const * pointer from const *'.  So, for the time being, I simply
  364.      cast it (char *) and avoid using -Wcast-qual.  */
  365.  
  366.   message = re_compile_pattern ((char *) string, strlen (string), pattern);
  367.   if (message)
  368.     {
  369.       fprintf (stderr, "* error in `%s'\n", string);
  370.       fprintf (stderr, "* %s\n", message);
  371.       exit (1);
  372.     }
  373.  
  374.   /* Note that the fastmap should be explicitely recompiled for `re_match',
  375.      but `re_search' is always called sooner, which automatically compiles
  376.      the fastmap if this has not been done yet.  So there is no real danger.
  377.  
  378.      re_compile_fastmap (pattern); */
  379.  
  380.   /* Do not waste extra allocated space.  */
  381.  
  382.   if (pattern->allocated > pattern->used)
  383.     {
  384.       pattern->buffer = (char *) xrealloc (pattern->buffer, pattern->used);
  385.       pattern->allocated = pattern->used;
  386.     }
  387.  
  388.   return pattern;
  389. }
  390.  
  391.  
  392. /* This will initialize various tables for pattern match and compiles some
  393.    regexps.  */
  394.  
  395. void
  396. #ifndef __STDC__
  397. initialize_regex ()
  398. #else
  399. initialize_regex (void)
  400. #endif
  401. {
  402.   int character;        /* character value */
  403.  
  404.   /* Initialize the regex syntax table.  */
  405.  
  406.   for (character = 0; character < (1 << BYTEWIDTH); character++)
  407.     syntax_table[character] = (isalpha (character) ? Sword : 0);
  408.  
  409.   re_syntax_table = syntax_table;
  410.  
  411.   /* Initialize the case folding table.  */
  412.  
  413.   if (fold_lower_to_upper)
  414.     {
  415.       for (character = 0; character < (1 << BYTEWIDTH); character++)
  416.     folded_chars[character]
  417.       = (syntax_table[character] == Sword && (character & 040))
  418.         ? (character & ~040) : character;
  419.     }
  420.  
  421.   /* Unless the user already provided a description of the end of line or
  422.      end of sentence sequence, select an end of line sequence to compile.
  423.      If the user provided an empty definition, thus disabling end of line
  424.      or sentence feature, make it NULL to speed up tests.  If ptx
  425.      compatibility is enabled, use end of lines.  If disabled, use end of
  426.      sentence, like GNU emacs'.  */
  427.  
  428.   if (context_regex_string)
  429.     {
  430.       if (!*context_regex_string)
  431.     context_regex_string = NULL;
  432.     }
  433.   else
  434.     {
  435. #ifdef PTX_COMPATIBILITY
  436.       context_regex_string = "\n";
  437. #else
  438.       context_regex_string = (input_reference ? "\n"
  439.                   : "[.?!][]\"')}]*\\($\\|\t\\|  \\)[ \t\n]*");
  440. #endif
  441.     }
  442.  
  443.   if (context_regex_string)
  444.     context_regex = alloc_and_compile_regex (context_regex_string);
  445.  
  446.   /* If the user has already provided a non-empty regexp to describe
  447.      words, compile it.  Else, unless this has already been done through
  448.      a user provided Break character file, construct a fastmap of
  449.      characters that may appear in a word.  If ptx compatibility enabled,
  450.      include almost everything, even punctuations; stop only on white
  451.      space.  If disabled, include only letters of the underlying
  452.      character set.  */
  453.  
  454.   if (word_regex_string && *word_regex_string)
  455.     word_regex = alloc_and_compile_regex (word_regex_string);
  456.   else if (!break_file)
  457.     {
  458. #ifdef PTX_COMPATIBILITY
  459.  
  460.       /* Simulate [^ \t\n]+.  */
  461.  
  462.       memset (word_fastmap, 1, 1 << BYTEWIDTH);
  463.       word_fastmap[' '] = 0;
  464.       word_fastmap['\t'] = 0;
  465.       word_fastmap['\n'] = 0;
  466. #else
  467.  
  468.       /* Simulate \w+.  */
  469.  
  470.       for (character = 0; character < (1 << BYTEWIDTH); character++)
  471.     word_fastmap[character] = syntax_table[character] == Sword;
  472. #endif
  473.     }
  474. }
  475.  
  476.  
  477. /* This routine will attempt to swallow a whole file name FILE_NAME into a
  478.    contiguous region of memory and return a description of it into BLOCK.
  479.    Standard input is assumed whenever FILE_NAME is NULL, empty or "-".
  480.  
  481.    Previously, in some cases, white space compression was attempted while
  482.    inputting text.  This was defeating some regexps like default end of
  483.    sentence, which checks for two consecutive spaces.  If white space
  484.    compression is ever reinstated, it should be in output routines.  */
  485.  
  486. void
  487. #ifndef __STDC__
  488. swallow_file_in_memory (file_name, block)
  489.      char *file_name;
  490.      BLOCK *block;
  491. #else
  492. swallow_file_in_memory (const char *file_name, BLOCK *block)
  493. #endif
  494. {
  495.   int file_handle;        /* file descriptor number */
  496.   struct stat stat_block;    /* stat block for file */
  497.   int allocated_length;        /* allocated length of memory buffer */
  498.   int used_length;        /* used length in memory buffer */
  499.   int read_length;        /* number of character gotten on last read */
  500.  
  501.   /* As special cases, a file name which is NULL or "-" indicates standard
  502.      input, which is already opened.  In all other cases, open the file from
  503.      its name.  */ 
  504.  
  505.   if (!file_name || !*file_name || strcmp (file_name, "-") == 0)
  506.     file_handle = fileno (stdin);
  507.   else
  508.     if ((file_handle = open (file_name, O_RDONLY)) < 0)
  509.       perror_and_exit (file_name);
  510.  
  511.   /* If the file is a plain, regular file, allocate the memory buffer all at
  512.      once and swallow the file in one blow.  In other cases, read the file
  513.      repeatedly in smaller chunks until we have it all, reallocating memory
  514.      once in a while, as we go.  */
  515.  
  516.   if (fstat (file_handle, &stat_block) < 0)
  517.     perror_and_exit (file_name);
  518.  
  519.   if ((stat_block.st_mode & S_IFMT) == S_IFREG)
  520.     {
  521.       block->start = (char *) xmalloc ((int) stat_block.st_size);
  522.  
  523.       if (read (file_handle, block->start, (int) stat_block.st_size)
  524.       != stat_block.st_size)
  525.     perror_and_exit (file_name);
  526.  
  527.       block->end = block->start + stat_block.st_size;
  528.     }
  529.   else
  530.     {
  531.       block->start = (char *) xmalloc (1 << SWALLOW_REALLOC_LOG);
  532.       used_length = 0;
  533.       allocated_length = (1 << SWALLOW_REALLOC_LOG);
  534.  
  535.       while ((read_length = read (file_handle,
  536.                   block->start + used_length,
  537.                   allocated_length - used_length)) > 0)
  538.     {
  539.       used_length += read_length;
  540.       if (used_length == allocated_length)
  541.         {
  542.           allocated_length += (1 << SWALLOW_REALLOC_LOG);
  543.           block->start
  544.         = (char *) xrealloc (block->start, allocated_length);
  545.         }
  546.     }
  547.  
  548.       if (read_length < 0)
  549.     perror_and_exit (file_name);
  550.  
  551.       block->end = block->start + used_length;
  552.     }
  553.  
  554.   /* Close the file, but only if it was not the standard input.  */
  555.  
  556.   if (file_handle != fileno (stdin))
  557.     close (file_handle);
  558. }
  559.  
  560. /* Sort and search routines.  */
  561.  
  562.  
  563. /* Compare two words, FIRST and SECOND, and return 0 if they are identical.
  564.    Return less than 0 if the first word goes before the second; return
  565.    greater than 0 if the first word goes after the second.
  566.  
  567.    If a word is indeed a prefix of the other, the shorter should go first.
  568. */
  569.  
  570. int
  571. #ifndef __STDC__
  572. compare_words (first, second)
  573.      WORD *first;
  574.      WORD *second;
  575. #else
  576. compare_words (WORD *first, WORD *second)
  577. #endif
  578. {
  579.   int length;            /* minimum of two lengths */
  580.   int counter;            /* cursor in words */
  581.   int value;            /* value of comparison */
  582.  
  583.   length = first->size < second->size ? first->size : second->size;
  584.  
  585.   if (fold_lower_to_upper)
  586.     {
  587.       for (counter = 0; counter < length; counter++)
  588.     {
  589.       value = (folded_chars [(unsigned char) (first->start[counter])]
  590.            - folded_chars [(unsigned char) (second->start[counter])]);
  591.       if (value != 0)
  592.         return value;
  593.     }
  594.     }
  595.   else
  596.     {
  597.       for (counter = 0; counter < length; counter++)
  598.     {
  599.       value = ((unsigned char) first->start[counter]
  600.            - (unsigned char) second->start[counter]);
  601.       if (value != 0)
  602.         return value;
  603.     }
  604.     }
  605.  
  606.   return first->size - second->size;
  607. }
  608.  
  609.  
  610. /* Decides which of two OCCURS, FIRST or SECOND, should lexicographically go
  611.    first.  In case of a tie, preserve the original order through a pointer
  612.    comparison.  */
  613.  
  614. int
  615. #ifndef __STDC__
  616. compare_occurs (first, second)
  617.      OCCURS *first;
  618.      OCCURS *second;
  619. #else
  620. compare_occurs (OCCURS *first, OCCURS *second)
  621. #endif
  622. {
  623.   int value;
  624.  
  625.   value = compare_words (&first->key, &second->key);
  626.   return value == 0 ? first->key.start - second->key.start : value;
  627. }
  628.  
  629.  
  630. /* Return !0 if WORD appears in TABLE.  Uses a binary search.  */
  631.  
  632. int
  633. #ifndef __STDC__
  634. search_table (word, table)
  635.      WORD *word;
  636.      WORD_TABLE *table;
  637. #else
  638. search_table (WORD *word, WORD_TABLE *table)
  639. #endif
  640. {
  641.   int lowest;            /* current lowest possible index */
  642.   int highest;            /* current highest possible index */
  643.   int middle;            /* current middle index */
  644.   int value;            /* value from last comparison */
  645.  
  646.   lowest = 0;
  647.   highest = table->length - 1;
  648.   while (lowest <= highest)
  649.     {
  650.       middle = (lowest + highest) / 2;
  651.       value = compare_words (word, table->start + middle);
  652.       if (value < 0)
  653.     highest = middle - 1;
  654.       else if (value > 0)
  655.     lowest = middle + 1;
  656.       else
  657.     return 1;
  658.     }
  659.   return 0;
  660. }
  661.  
  662.  
  663. /* Sort the whole occurs table in memory.  Presumably, `qsort' does not take
  664.    intermediate copies or table elements, so the sort will be stabilized
  665.    throught the comparison routine.  */
  666.  
  667. void
  668. #ifndef __STDC__
  669. sort_found_occurs ()
  670. #else
  671. sort_found_occurs (void)
  672. #endif
  673. {
  674.  
  675.   /* Only one language for the time being.  */
  676.  
  677.   qsort (occurs_table[0], number_of_occurs[0],
  678.      sizeof_occurs, compare_occurs);
  679. }
  680.  
  681. /* Parameter files reading routines.  */
  682.  
  683.  
  684. /* Read a file named FILE_NAME, containing a set of break characters.  Build
  685.    a content to the array word_fastmap in which all characters are allowed
  686.    except those found in the file.  Characters may be repeated.  */
  687.  
  688. void
  689. #ifndef __STDC__
  690. digest_break_file (file_name)
  691.      char *file_name;
  692. #else
  693. digest_break_file (const char *file_name)
  694. #endif
  695. {
  696.   BLOCK file_contents;        /* to receive a copy of the file */
  697.   char *cursor;            /* cursor in file copy */
  698.  
  699.   swallow_file_in_memory (file_name, &file_contents);
  700.  
  701.   /* Make the fastmap and record the file contents in it.  */
  702.  
  703.   memset (word_fastmap, 1, 1 << BYTEWIDTH);
  704.   for (cursor = file_contents.start; cursor < file_contents.end; cursor++)
  705.     word_fastmap[(unsigned char) *cursor] = 0;
  706.  
  707. #ifdef PTX_COMPATIBILITY
  708.  
  709.   /* If ptx compatibility is enabled, spaces, tabs and newlines are
  710.      always considered as break characters even if not included in the
  711.      break file.  If disabled, the only way to avoid newline as a break
  712.      character is to write all the break characters in the file with no
  713.      newline at all, not even at the end of the file.  */
  714.  
  715.   word_fastmap[' '] = 0;
  716.   word_fastmap['\t'] = 0;
  717.   word_fastmap['\n'] = 0;
  718.  
  719. #endif
  720.  
  721.   /* Return the space of the file, which is no more required.  */
  722.  
  723.   free (file_contents.start);
  724. }
  725.  
  726. /* Read a file named FILE_NAME, containing one word per line, then construct
  727.    in TABLE a table of WORD descriptors for them.  The routine swallows the
  728.    whole file in memory; this is at the expense of space needed for
  729.    newlines, which are useless; however, the reading is fast.  */
  730.  
  731. void
  732. #ifndef __STDC__
  733. digest_word_file (file_name, table)
  734.      char *file_name;
  735.      WORD_TABLE *table;
  736. #else
  737. digest_word_file (const char *file_name, WORD_TABLE *table)
  738. #endif
  739. {
  740.   BLOCK file_contents;        /* to receive a copy of the file */
  741.   char *cursor;            /* cursor in file copy */
  742.   char *word_start;        /* start of the current word */
  743.  
  744.   swallow_file_in_memory (file_name, &file_contents);
  745.  
  746.   table->start = NULL;
  747.   table->length = 0;
  748.  
  749.   /* Read the whole file.  */
  750.  
  751.   cursor = file_contents.start;
  752.   while (cursor < file_contents.end)
  753.     {
  754.  
  755.       /* Read one line, and save the word in contains.  */
  756.  
  757.       word_start = cursor;
  758.       while (cursor < file_contents.end && *cursor != '\n')
  759.     cursor++;
  760.  
  761.       /* Record the word in table if it is not empty.  */
  762.  
  763.       if (cursor > word_start)
  764.     {
  765.       ALLOC_NEW_WORD (table);
  766.       table->start[table->length].start = word_start;
  767.       table->start[table->length].size = cursor - word_start;
  768.       table->length++;
  769.     }
  770.  
  771.       /* This test allows for an incomplete line at end of file.  */
  772.  
  773.       if (cursor < file_contents.end)
  774.     cursor++;
  775.     }
  776.  
  777.   /* Finally, sort all the words read.  */
  778.  
  779. #ifdef DEBUGGING
  780.   dump_table (table);
  781. #endif
  782.   qsort (table->start, table->length, sizeof (WORD), compare_words);
  783. #ifdef DEBUGGING
  784.   dump_table (table);
  785. #endif
  786. }
  787.  
  788.  
  789. /* Keyword recognition and selection.  */
  790.  
  791.  
  792. /* For each keyword in the source text, constructs an OCCURS structure.  */
  793.  
  794. void
  795. #ifndef __STDC__
  796. find_occurs_in_text ()
  797. #else
  798. find_occurs_in_text (void)
  799. #endif
  800. {
  801.   char *cursor;            /* for scanning the source text */
  802.   char *scan;            /* for scanning the source text also */
  803.   char *line_start;        /* start of the current input line */
  804.   char *line_scan;        /* newlines scanned until this point */
  805.   int reference_length;        /* length of reference in input mode */
  806.   WORD possible_key;        /* possible key, to ease searches */
  807.   OCCURS *occurs_cursor;    /* current OCCURS under construction */
  808.  
  809.   char *context_start;        /* start of left context */
  810.   char *context_end;        /* end of right context */
  811.   char *next_context_start;    /* next start of left context */
  812.  
  813.   /* Tracking where lines start is helpful for reference processing.  In
  814.      auto reference mode, this allows counting lines.  In input reference
  815.      mode, this permits finding the beginning of the references.
  816.  
  817.      The first line begins with the file, skip immediately this very first
  818.      reference in input reference mode, to help further rejection any word
  819.      found inside it.  Also, unconditionnaly assigning these variable has
  820.      the happy effect of shutting up lint.  */
  821.  
  822.   line_start = text_buffer.start;
  823.   line_scan = line_start;
  824.   if (input_reference)
  825.     {
  826.       SKIP_NON_WHITE (line_scan, text_buffer.end);
  827.       reference_length = line_scan - line_start;
  828.       SKIP_WHITE (line_scan, text_buffer.end);
  829.     }
  830.  
  831.   /* Process the whole buffer, one line or one sentence at a time.  */
  832.  
  833.   for (cursor = text_buffer.start;
  834.        cursor < text_buffer.end;
  835.        cursor = next_context_start)
  836.     {
  837.  
  838.       /* `context_start' gets initialized before the processing of each
  839.      line, or once for the whole buffer if no end of line or sentence
  840.      sequence separator.  */
  841.  
  842.       context_start = cursor;
  843.  
  844.       /* If a end of line or end of sentence sequence is defined and
  845.      non-empty, `next_context_start' will be recomputed to be the end of
  846.      each line or sentence, before each one is processed.  If no such
  847.      sequence, then `next_context_start' is set at the end of the whole
  848.      buffer, which is then considered to be a single line or sentence.
  849.      This test also accounts for the case of an incomplete line or
  850.      sentence at the end of the buffer.  */
  851.  
  852.       if (context_regex_string
  853.       && (re_search (context_regex, cursor, text_buffer.end - cursor,
  854.              0, text_buffer.end - cursor, &context_regs)
  855.           >= 0))
  856.     next_context_start = cursor + context_regs.end[0];
  857.  
  858.       else
  859.     next_context_start = text_buffer.end;
  860.  
  861.       /* Include the separator into the right context, but not any suffix
  862.      white space in this separator; this insures it will be seen in
  863.      output and will not take more space than necessary.  */
  864.  
  865.       context_end = next_context_start;
  866.       SKIP_WHITE_BACKWARDS (context_end, context_start);
  867.  
  868.       /* Read and process a single input line or sentence, one word at a
  869.      time.  */
  870.  
  871.       while (1)
  872.     {
  873.       if (word_regex)
  874.  
  875.         /* If a word regexp has been compiled, use it to skip at the
  876.            beginning of the next word.  If there is no such word, exit
  877.            the loop.  */
  878.  
  879.         {
  880.           if (re_search (word_regex, cursor, context_end - cursor,
  881.                  0, context_end - cursor, &word_regs)
  882.           < 0)
  883.         break;
  884.         }
  885.       else
  886.  
  887.         /* Avoid re_search and use the fastmap to skip to the beginning
  888.            of the next word, but update word_regs.start[0] and
  889.            word_regs.end[0] as if re_search had been called.  If there
  890.            is no more word in the buffer, exit the loop.  */
  891.  
  892.         {
  893.           scan = cursor;
  894.           while (scan < context_end
  895.              && !word_fastmap[(unsigned char) *scan])
  896.         scan++;
  897.  
  898.           if (scan == context_end)
  899.         break;
  900.  
  901.           word_regs.start[0] = scan - cursor;
  902.  
  903.           while (scan < context_end
  904.              && word_fastmap[(unsigned char) *scan])
  905.         scan++;
  906.  
  907.           word_regs.end[0] = scan - cursor;
  908.         }
  909.  
  910.       /* Skip right to the beginning of the found word.  */
  911.  
  912.       cursor += word_regs.start[0];
  913.  
  914.       /* Skip any zero length word.  Just advance a single position,
  915.          then go fetch the next word.  */
  916.  
  917.       if (word_regs.end[0] == word_regs.start[0])
  918.         {
  919.           cursor++;
  920.           continue;
  921.         }
  922.  
  923.       /* This is a genuine, non empty word, so save it as a possible
  924.          key.  Then skip over it.  Also, maintain the maximum length of
  925.          all words read so far.  It is mandatory to take the maximum
  926.          length of all words in the file, without considering if they
  927.          are actually kept or rejected, because backward jumps at output
  928.          generation time may fall in *any* word.  */
  929.  
  930.       possible_key.start = cursor;
  931.       possible_key.size = word_regs.end[0] - word_regs.start[0];
  932.       cursor += possible_key.size;
  933.  
  934.       if (possible_key.size > maximum_word_length)
  935.         maximum_word_length = possible_key.size;
  936.  
  937.       /* In input reference mode, update `line_start' from its previous
  938.          value.  Count the lines just in case auto reference mode is
  939.          also selected. If it happens that the word just matched is
  940.          indeed part of a reference; just ignore it.  */
  941.  
  942.       if (input_reference)
  943.         {
  944.           while (line_scan < possible_key.start)
  945.         if (*line_scan == '\n')
  946.           {
  947.             total_line_count++;
  948.             line_scan++;
  949.             line_start = line_scan;
  950.             SKIP_NON_WHITE (line_scan, text_buffer.end);
  951.             reference_length = line_scan - line_start;
  952.           }
  953.         else
  954.           line_scan++;
  955.           if (line_scan > possible_key.start)
  956.         continue;
  957.         }
  958.  
  959.       /* Ignore the word if an `Ignore words' table exists and if it is
  960.          part of it.  Also ignore the word if an `Only words' table and
  961.          if it is *not* part of it.
  962.  
  963.          It is allowed that both tables be used at once, even if this
  964.          may look strange for now.  Just ignore a word that would appear
  965.          in both.  If regexps are eventually implemented for these
  966.          tables, the Ignore table could then reject words that would
  967.          have been previously accepted by the Only table.  */
  968.  
  969.       if (ignore_file && search_table (&possible_key, &ignore_table))
  970.         continue;
  971.       if (only_file && !search_table (&possible_key, &only_table))
  972.         continue;
  973.  
  974.       /* A non-empty word has been found.  First of all, insure
  975.          proper allocation of the next OCCURS, and make a pointer to
  976.          where it will be constructed.  */
  977.  
  978.       ALLOC_NEW_OCCURS (0);
  979.       occurs_cursor = (OCCURS *)
  980.         ((char *) occurs_table[0] + sizeof_occurs * number_of_occurs[0]);
  981.  
  982.       /* Define the refence field, if any.  */
  983.  
  984.       if (auto_reference)
  985.         {
  986.  
  987.           /* While auto referencing, update `line_start' from its
  988.          previous value, counting lines as we go.  If input
  989.          referencing at the same time, `line_start' has been
  990.          advanced earlier, and the following loop is never really
  991.          executed.  */
  992.  
  993.           while (line_scan < possible_key.start)
  994.         if (*line_scan == '\n')
  995.           {
  996.             total_line_count++;
  997.             line_scan++;
  998.             line_start = line_scan;
  999.             SKIP_NON_WHITE (line_scan, text_buffer.end);
  1000.           }
  1001.         else
  1002.           line_scan++;
  1003.  
  1004.           occurs_cursor->reference = total_line_count;
  1005.         }
  1006.       else if (input_reference)
  1007.         {
  1008.  
  1009.           /* If only input referencing, `line_start' has been computed
  1010.          earlier to detect the case the word matched would be part
  1011.          of the reference.  The reference position is simply the
  1012.          value of `line_start'.  */
  1013.  
  1014.           occurs_cursor->reference
  1015.         = (DELTA) (line_start - possible_key.start);
  1016.           if (reference_length > reference_max_width)
  1017.         reference_max_width = reference_length;
  1018.         }
  1019.  
  1020.       /* Exclude the reference from the context in simple cases.  */
  1021.  
  1022.       if (input_reference && line_start == context_start)
  1023.         {
  1024.           SKIP_NON_WHITE (context_start, context_end);
  1025.           SKIP_WHITE (context_start, context_end);
  1026.         }
  1027.  
  1028.       /* Completes the OCCURS structure.  */
  1029.  
  1030.       occurs_cursor->key = possible_key;
  1031.       occurs_cursor->left = context_start - possible_key.start;
  1032.       occurs_cursor->right = context_end - possible_key.start;
  1033.  
  1034.       number_of_occurs[0]++;
  1035.     }
  1036.     }
  1037. }
  1038.  
  1039. /* Formatting and actual output - service routines.  */
  1040.  
  1041.  
  1042. /* Prints some NUMBER of spaces on stdout.  */
  1043.  
  1044. void
  1045. #ifndef __STDC__
  1046. print_spaces (number)
  1047.      int number;
  1048. #else
  1049. print_spaces (int number)
  1050. #endif
  1051. {
  1052.   int counter;
  1053.  
  1054.   for (counter = number; counter > 0; counter--)
  1055.     putchar (' ');
  1056. }
  1057.  
  1058.  
  1059. /* Prints the field provided by FIELD.  */
  1060.  
  1061. void
  1062. #ifndef __STDC__
  1063. print_field (field)
  1064.      BLOCK field;
  1065. #else
  1066. print_field (BLOCK field)
  1067. #endif
  1068. {
  1069.   char *cursor;            /* Cursor in field to print */
  1070.   int character;        /* Current character */
  1071.   int base;            /* Base character, without diacritic */
  1072.   int diacritic;        /* Diacritic code for the character */
  1073.  
  1074.   /* Whitespace is not really compressed.  Instead, each white space
  1075.      character (tab, vt, ht etc.) is printed as one single space.  */
  1076.  
  1077.   for (cursor = field.start; cursor < field.end; cursor++)
  1078.     {
  1079.       character = (unsigned char) *cursor;
  1080.       if (edited_flag[character])
  1081.     {
  1082.  
  1083.       /* First check if this is a diacriticized character.  All this
  1084.          stuff should be done by "ctype.c" specific routines, at least
  1085.          because the diacritic codes are quite "ctype.c" dependent.
  1086.          I'll do it here for now, and will move it elsewhere when the
  1087.          code will have settle down a little.
  1088.  
  1089.          This works only for TeX.  I do not know how diacriticized
  1090.          letters work with `roff'.  Please someone explain it to me!  */
  1091.  
  1092.       diacritic = todiac (character);
  1093.       if (diacritic != 0 && output_format == TEX_FORMAT)
  1094.         {
  1095.           base = tobase (character);
  1096.           switch (diacritic)
  1097.         {
  1098.  
  1099.         case 1:        /* Latin diphtongues */
  1100.           switch (base)
  1101.             {
  1102.             case 'o':
  1103.               printf ("\\oe{}");
  1104.               break;
  1105.  
  1106.             case 'O':
  1107.               printf ("\\OE{}");
  1108.               break;
  1109.  
  1110.             case 'a':
  1111.               printf ("\\ae{}");
  1112.               break;
  1113.  
  1114.             case 'A':
  1115.               printf ("\\AE{}");
  1116.               break;
  1117.  
  1118.             default:
  1119.               putchar (' ');
  1120.             }
  1121.           break;
  1122.  
  1123.         case 2:        /* Acute accent */
  1124.           printf ("\\'%s%c", (base == 'i' ? "\\" : ""), base);
  1125.           break;
  1126.  
  1127.         case 3:        /* Grave accent */
  1128.           printf ("\\`%s%c", (base == 'i' ? "\\" : ""), base);
  1129.           break;
  1130.  
  1131.         case 4:        /* Circumflex accent */
  1132.           printf ("\\^%s%c", (base == 'i' ? "\\" : ""), base);
  1133.           break;
  1134.  
  1135.         case 5:        /* Diaeresis */
  1136.           printf ("\\\"%s%c", (base == 'i' ? "\\" : ""), base);
  1137.           break;
  1138.  
  1139.         case 6:        /* Tilde accent */
  1140.           printf ("\\~%s%c", (base == 'i' ? "\\" : ""), base);
  1141.           break;
  1142.  
  1143.         case 7:        /* Cedilla */
  1144.           printf ("\\c{%c}", base);
  1145.           break;
  1146.  
  1147.         case 8:        /* Small circle beneath */
  1148.           switch (base)
  1149.             {
  1150.             case 'a':
  1151.               printf ("\\aa{}");
  1152.               break;
  1153.  
  1154.             case 'A':
  1155.               printf ("\\AA{}");
  1156.               break;
  1157.  
  1158.             default:
  1159.               putchar (' ');
  1160.             }
  1161.           break;
  1162.  
  1163.         case 9:        /* Strike through */
  1164.           switch (base)
  1165.             {
  1166.             case 'o':
  1167.               printf ("\\o{}");
  1168.               break;
  1169.  
  1170.             case 'O':
  1171.               printf ("\\O{}");
  1172.               break;
  1173.  
  1174.             default:
  1175.               putchar (' ');
  1176.             }
  1177.           break;
  1178.         }
  1179.         }
  1180.       else
  1181.  
  1182.         /* This is not a diacritic character, so handle cases which are
  1183.            really specific to `roff' or TeX.  All white space processing
  1184.            is done as the default case of this switch.  */
  1185.  
  1186.         switch (character)
  1187.           {
  1188.           case '"':
  1189.         /* In roff output format, double any quote.  */
  1190.         putchar ('"');
  1191.         putchar ('"');
  1192.         break;
  1193.  
  1194.           case '$':
  1195.           case '%':
  1196.           case '&':
  1197.           case '#':
  1198.           case '_':
  1199.         /* In TeX output format, precede these with a backslash.  */
  1200.         putchar ('\\');
  1201.         putchar (character);
  1202.         break;
  1203.  
  1204.           case '{':
  1205.           case '}':
  1206.         /* In TeX output format, precede these with a backslash and
  1207.            force mathematical mode.  */
  1208.         printf ("$\\%c$", character);
  1209.         break;
  1210.  
  1211.           case '\\':
  1212.         /* In TeX output mode, request production of a backslash.  */
  1213.         printf ("\\backslash{}");
  1214.         break;
  1215.  
  1216.           default:
  1217.         /* Any other flagged character produces a single space.  */
  1218.         putchar (' ');
  1219.           }
  1220.     }
  1221.       else
  1222.     putchar (*cursor);
  1223.     }
  1224. }
  1225.  
  1226.  
  1227. /* Formatting and actual output - planning routines.  */
  1228.  
  1229.  
  1230. /* From information collected from command line options and input file
  1231.    readings, compute and fix some output parameter values.  */
  1232.  
  1233. void
  1234. #ifndef __STDC__
  1235. fix_output_parameters ()
  1236. #else
  1237. fix_output_parameters (void)
  1238. #endif
  1239. {
  1240.   int file_index;        /* index in text input file arrays */
  1241.   int line_ordinal;        /* line ordinal value for reference */
  1242.   char ordinal_string[12];    /* edited line ordinal for reference */
  1243.   int reference_width;        /* width for the whole reference */
  1244.   int character;        /* character ordinal */
  1245.   const char *cursor;        /* cursor in some constant strings */
  1246.  
  1247.   /* In auto reference mode, the maximum width of this field is
  1248.      precomputed and subtracted from the overall line width.  Add one for
  1249.      the column which separate the file name from the line number.  */
  1250.  
  1251.   if (auto_reference)
  1252.     {
  1253.       reference_max_width = 0;
  1254.       for (file_index = 0; file_index < number_input_files; file_index++)
  1255.     {
  1256.       line_ordinal = file_line_count[file_index] + 1;
  1257.       if (file_index > 0)
  1258.         line_ordinal -= file_line_count[file_index - 1];
  1259.       sprintf (ordinal_string, "%d", line_ordinal);
  1260.       reference_width = strlen (ordinal_string);
  1261.       if (input_file_name[file_index])
  1262.         reference_width += strlen (input_file_name[file_index]);
  1263.       if (reference_width > reference_max_width)
  1264.         reference_max_width = reference_width;
  1265.     }
  1266.       reference_max_width++;
  1267.       reference.start = (char *) xmalloc (reference_max_width + 1);
  1268.     }
  1269.  
  1270.   /* If the reference appears to the left of the output line, reserve some
  1271.      space for it right away, including one gap size.  */
  1272.  
  1273.   if ((auto_reference || input_reference) && !right_reference)
  1274.     line_width -= reference_max_width + gap_size;
  1275.  
  1276.   /* The output lines, minimally, will contain from left to right a left
  1277.      context, a gap, and a keyword followed by the right context with no
  1278.      special intervening gap.  Half of the line width is dedicated to the
  1279.      left context and the gap, the other half is dedicated to the keyword
  1280.      and the right context; these values are computed once and for all here.
  1281.      There also are tail and head wrap around fields, used when the keywork
  1282.      is near the beginning or the end of the line, or when some long word
  1283.      cannot fit in, but leave place from wrapped around shorter words.  The
  1284.      maximum width of these fields are recomputed seperately for each line,
  1285.      on a case by case basis.  It is worth noting that it cannot happen that
  1286.      both the tail and head fields are used at once.  */
  1287.  
  1288.   half_line_width = line_width / 2;
  1289.   before_max_width = half_line_width - gap_size;
  1290.   keyafter_max_width = half_line_width;
  1291.  
  1292.   /* If truncation_string is the empty string, make it NULL to speed up
  1293.      tests.  In this case, truncation_string_length will never get used, so
  1294.      there is no need to set it.  */
  1295.  
  1296.   if (truncation_string && *truncation_string)
  1297.     truncation_string_length = strlen (truncation_string);
  1298.   else
  1299.     truncation_string = NULL;
  1300.  
  1301. #ifdef PTX_COMPATIBILITY
  1302.  
  1303.   /* I never figured out exactly how UNIX' ptx plan the output width of
  1304.      its various fields.  The following formula does not completely
  1305.      imitate UNIX' ptx if ptx compatibility is enabled, but almost.  If
  1306.      disabled, rather compute the field widths correctly.  */
  1307.  
  1308.   keyafter_max_width -= 2 * truncation_string_length + 1;
  1309.  
  1310. #else /* not PTX_COMPATIBILITY */
  1311.  
  1312.   /* When flagging truncation at the left of the keyword, the truncation
  1313.      mark goes at the beginning of the before field, unless there is a
  1314.      head field, in which case the mark goes at the left of the head
  1315.      field.  When flagging truncation at the right of the keyward, the
  1316.      mark goes at the end of the keyafter field, unless there is a tail
  1317.      field, in which case the mark goes at the end of the tail field.
  1318.      So, only eight combination cases could arise for truncation marks:
  1319.      
  1320.      . None.
  1321.      . One beginning the before field.
  1322.      . One beginning the head field.
  1323.      . One ending the keyafter field.
  1324.      . One ending the tail field.
  1325.      . One beginning the before field, another ending the keyafter field.
  1326.      . One ending the tail field, another beginning the before field.
  1327.      . One ending the keyafter field, another beginning the head field. 
  1328.      
  1329.      So, there is at most two truncation marks, which could appear both
  1330.      on the left side of the center of the output line, both on the
  1331.      right side, or one on either side.  */
  1332.  
  1333.   before_max_width -= 2 * truncation_string_length;
  1334.   keyafter_max_width -= 2 * truncation_string_length;
  1335.  
  1336. #endif /* not PTX_COMPATIBILITY */
  1337.  
  1338.   /* Compute which characters need special output processing.  Initialize by
  1339.      flagging any white space character.  Complete the special character
  1340.      flagging according to selected output format.  */
  1341.  
  1342.   for (character = 0; character < (1 << BYTEWIDTH); character++)
  1343.     edited_flag[character] = isspace (character);
  1344.  
  1345.   switch (output_format)
  1346.     {
  1347.     case UNKNOWN_FORMAT:
  1348.       /* Should never happen.  */
  1349.  
  1350.     case DUMB_FORMAT:
  1351.       break;
  1352.  
  1353.     case ROFF_FORMAT:
  1354.  
  1355.       /* `Quote' characters should be doubled.  */
  1356.  
  1357.       edited_flag['"'] = 1;
  1358.  
  1359.       /* Any character with 8th bit set will print to a single space.
  1360.      Diacriticized characters do not work for `roff', because I do not
  1361.      how to do it.  Please someone tell me!  */
  1362.  
  1363.       for (character = 0200; character < (1 << BYTEWIDTH); character++)
  1364.     edited_flag[character] = 1;
  1365.       break;
  1366.  
  1367.     case TEX_FORMAT:
  1368.  
  1369.       /* Various characters need special processing.  */
  1370.  
  1371.       for (cursor = "$%&#_{}\\"; *cursor; cursor++)
  1372.     edited_flag[*cursor] = 1;
  1373.  
  1374.       /* Any character with 8th bit set will print to a single space, unless
  1375.      it is diacriticized.  */
  1376.  
  1377.       for (character = 0200; character < (1 << BYTEWIDTH); character++)
  1378.     edited_flag[character] = todiac (character) != 0;
  1379.       break;
  1380.     }
  1381. }
  1382.  
  1383.  
  1384. /* Compute the position and length of all the output fields, given a pointer
  1385.    to some OCCURS.  */
  1386.  
  1387. void
  1388. #ifndef __STDC__
  1389. define_all_fields (occurs)
  1390.      OCCURS *occurs;
  1391. #else
  1392. define_all_fields (OCCURS *occurs)
  1393. #endif
  1394. {
  1395.   int tail_max_width;        /* allowable width of tail field */
  1396.   int head_max_width;        /* allowable width of head field */
  1397.   char *cursor;            /* running cursor in source text */
  1398.   char *left_context_start;    /* start of left context */
  1399.   char *right_context_end;    /* end of right context */
  1400.   char *left_field_start;    /* conservative start for `head'/`before' */
  1401.   int file_index;        /* index in text input file arrays */
  1402.   const char *file_name;        /* file name for reference */
  1403.   int line_ordinal;        /* line ordinal for reference */
  1404.  
  1405.   /* Define `keyafter', start of left context and end of right context.
  1406.      `keyafter' starts at the saved position for keyword and extend to the
  1407.      right from the end of the keyword, eating separators or full words, but
  1408.      not beyond maximum allowed width for `keyafter' field or limit for the
  1409.      right context.  Suffix spaces will be removed afterwards.  */
  1410.  
  1411.   keyafter.start = occurs->key.start;
  1412.   keyafter.end = keyafter.start + occurs->key.size;
  1413.   left_context_start = keyafter.start + occurs->left;
  1414.   right_context_end = keyafter.start + occurs->right;
  1415.  
  1416.   cursor = keyafter.end;
  1417.   while (cursor < right_context_end
  1418.      && cursor <= keyafter.start + keyafter_max_width)
  1419.     {
  1420.       keyafter.end = cursor;
  1421.       SKIP_SOMETHING (cursor, right_context_end);
  1422.     }
  1423.   if (cursor <= keyafter.start + keyafter_max_width)
  1424.     keyafter.end = cursor;
  1425.  
  1426.   keyafter_truncation = truncation_string && keyafter.end < right_context_end;
  1427.  
  1428.   SKIP_WHITE_BACKWARDS (keyafter.end, keyafter.start);
  1429.  
  1430.   /* When the left context is wide, it might take some time to catch up from
  1431.      the left context boundary to the beginning of the `head' or `before'
  1432.      fields.  So, in this case, to speed the catchup, we jump back from the
  1433.      keyword, using some secure distance, possibly falling in the middle of
  1434.      a word.  A secure backward jump would be at least half the maximum
  1435.      width of a line, plus the size of the longest word met in the whole
  1436.      input.  We conclude this backward jump by a skip forward of at least
  1437.      one word.  In this manner, we should not inadvertently accept only part
  1438.      of a word.  From the reached point, when it will be time to fix the
  1439.      beginning of `head' or `before' fields, we will skip forward words or
  1440.      delimiters until we get sufficiently near.  */
  1441.  
  1442.   if (-occurs->left > half_line_width + maximum_word_length)
  1443.     {
  1444.       left_field_start
  1445.     = keyafter.start - (half_line_width + maximum_word_length);
  1446.       SKIP_SOMETHING (left_field_start, keyafter.start);
  1447.     }
  1448.   else
  1449.     left_field_start = keyafter.start + occurs->left;
  1450.  
  1451.   /* `before' certainly ends at the keyword, but not including separating
  1452.      spaces.  It starts after than the saved value for the left context, by
  1453.      advancing it until it falls inside the maximum allowed width for the
  1454.      before field.  There will be no prefix spaces either.  `before' only
  1455.      advances by skipping single separators or whole words. */
  1456.  
  1457.   before.start = left_field_start;
  1458.   before.end = keyafter.start;
  1459.   SKIP_WHITE_BACKWARDS (before.end, before.start);
  1460.  
  1461.   while (before.start + before_max_width < before.end)
  1462.     SKIP_SOMETHING (before.start, before.end);
  1463.  
  1464.   if (truncation_string)
  1465.     {
  1466.       cursor = before.start;
  1467.       SKIP_WHITE_BACKWARDS (cursor, text_buffer.start);
  1468.       before_truncation = cursor > left_context_start;
  1469.     }
  1470.   else
  1471.     before_truncation = 0;
  1472.  
  1473.   SKIP_WHITE (before.start, text_buffer.end);
  1474.  
  1475.   /* The tail could not take more columns than what has been left in the
  1476.      left context field, and a gap is mandatory.  It starts after the
  1477.      right context, and does not contain prefixed spaces.  It ends at
  1478.      the end of line, the end of buffer or when the tail field is full,
  1479.      whichever comes first.  It cannot contain only part of a word, and
  1480.      has no suffixed spaces.  */
  1481.  
  1482.   tail_max_width
  1483.     = before_max_width - (before.end - before.start) - gap_size;
  1484.  
  1485.   if (tail_max_width > 0)
  1486.     {
  1487.       tail.start = keyafter.end;
  1488.       SKIP_WHITE (tail.start, text_buffer.end);
  1489.  
  1490.       tail.end = tail.start;
  1491.       cursor = tail.end;
  1492.       while (cursor < right_context_end
  1493.          && cursor < tail.start + tail_max_width)
  1494.     {
  1495.       tail.end = cursor;
  1496.       SKIP_SOMETHING (cursor, right_context_end);
  1497.     }
  1498.  
  1499.       if (cursor < tail.start + tail_max_width)
  1500.     tail.end = cursor;
  1501.  
  1502.       if (tail.end > tail.start)
  1503.     {
  1504.       keyafter_truncation = 0;
  1505.       tail_truncation = truncation_string && tail.end < right_context_end;
  1506.     }
  1507.       else
  1508.     tail_truncation = 0;
  1509.  
  1510.       SKIP_WHITE_BACKWARDS (tail.end, tail.start);
  1511.     }
  1512.   else
  1513.     {
  1514.  
  1515.       /* No place left for a tail field.  */
  1516.  
  1517.       tail.start = NULL;
  1518.       tail.end = NULL;
  1519.       tail_truncation = 0;
  1520.     }
  1521.  
  1522.   /* `head' could not take more columns than what has been left in the right
  1523.      context field, and a gap is mandatory.  It ends before the left
  1524.      context, and does not contain suffixed spaces.  Its pointer is advanced
  1525.      until the head field has shrunk to its allowed width.  It cannot
  1526.      contain only part of a word, and has no suffixed spaces.  */
  1527.  
  1528.   head_max_width
  1529.     = keyafter_max_width - (keyafter.end - keyafter.start) - gap_size;
  1530.  
  1531.   if (head_max_width > 0)
  1532.     {
  1533.       head.end = before.start;
  1534.       SKIP_WHITE_BACKWARDS (head.end, text_buffer.start);
  1535.  
  1536.       head.start = left_field_start;
  1537.       while (head.start + head_max_width < head.end)
  1538.     SKIP_SOMETHING (head.start, head.end);
  1539.  
  1540.       if (head.end > head.start)
  1541.     {
  1542.       before_truncation = 0;
  1543.       head_truncation = (truncation_string
  1544.                  && head.start > left_context_start);
  1545.     }
  1546.       else
  1547.     head_truncation = 0;
  1548.  
  1549.       SKIP_WHITE (head.start, head.end);
  1550.     }
  1551.   else
  1552.     {
  1553.  
  1554.       /* No place left for a head field.  */
  1555.  
  1556.       head.start = NULL;
  1557.       head.end = NULL;
  1558.       head_truncation = 0;
  1559.     }
  1560.  
  1561.   if (auto_reference)
  1562.     {
  1563.  
  1564.       /* Construct the reference text in preallocated space from the file
  1565.      name and the line number.  Find out in which file the reference
  1566.      occured.  Standard input yields an empty file name.  Insure line
  1567.      numbers are one based, even if they are computed zero based.  */
  1568.  
  1569.       file_index = 0;
  1570.       while (file_line_count[file_index] < occurs->reference)
  1571.     file_index++;
  1572.  
  1573.       file_name = input_file_name[file_index];
  1574.       if (!file_name)
  1575.     file_name = "";
  1576.  
  1577.       line_ordinal = occurs->reference + 1;
  1578.       if (file_index > 0)
  1579.     line_ordinal -= file_line_count[file_index - 1];
  1580.  
  1581.       sprintf (reference.start, "%s:%d", file_name, line_ordinal);
  1582.       reference.end = reference.start + strlen (reference.start);
  1583.     }
  1584.   else if (input_reference)
  1585.     {
  1586.  
  1587.       /* Reference starts at saved position for reference and extends right
  1588.      until some white space is met.  */
  1589.  
  1590.       reference.start = keyafter.start + (DELTA) occurs->reference;
  1591.       reference.end = reference.start;
  1592.       SKIP_NON_WHITE (reference.end, right_context_end);
  1593.     }
  1594. }
  1595.  
  1596.  
  1597. /* Formatting and actual output - control routines.  */
  1598.  
  1599.  
  1600. /* Output the current output fields as one line for `troff' or `nroff'.  */
  1601.  
  1602. void
  1603. #ifndef __STDC__
  1604. output_one_roff_line ()
  1605. #else
  1606. output_one_roff_line (void)
  1607. #endif
  1608. {
  1609.   /* Output the `tail' field.  */
  1610.  
  1611.   printf (".xx \"");
  1612.   print_field (tail);
  1613.   if (tail_truncation)
  1614.     printf ("%s", truncation_string);
  1615.   putchar ('"');
  1616.  
  1617.   /* Output the `before' field.  */
  1618.  
  1619.   printf (" \"");
  1620.   if (before_truncation)
  1621.     printf ("%s", truncation_string);
  1622.   print_field (before);
  1623.   putchar ('"');
  1624.  
  1625.   /* Output the `keyafter' field.  */
  1626.  
  1627.   printf (" \"");
  1628.   print_field (keyafter);
  1629.   if (keyafter_truncation)
  1630.     printf ("%s", truncation_string);
  1631.   putchar ('"');
  1632.  
  1633.   /* Output the `head' field.  */
  1634.  
  1635.   printf (" \"");
  1636.   if (head_truncation)
  1637.     printf ("%s", truncation_string);
  1638.   print_field (head);
  1639.   putchar ('"');
  1640.  
  1641.   /* Conditionnaly output the `reference' field.  */
  1642.  
  1643.   if (auto_reference || input_reference)
  1644.     {
  1645.       printf (" \"");
  1646.       print_field (reference);
  1647.       putchar ('"');
  1648.     }
  1649.  
  1650.   putchar ('\n');
  1651. }
  1652.  
  1653.  
  1654. /* Output the current output fields as one line for `TeX'.  */
  1655.  
  1656. void
  1657. #ifndef __STDC__
  1658. output_one_tex_line ()
  1659. #else
  1660. output_one_tex_line (void)
  1661. #endif
  1662. {
  1663.   BLOCK key;            /* key field, isolated */
  1664.   BLOCK after;            /* after field, isolated */
  1665.   char *cursor;            /* running cursor in source text */
  1666.  
  1667.   printf ("\\xx ");
  1668.   printf ("{");
  1669.   print_field (tail);
  1670.   printf ("}{");
  1671.   print_field (before);
  1672.   printf ("}{");
  1673.   key.start = keyafter.start;
  1674.   after.end = keyafter.end;
  1675.   cursor = keyafter.start;
  1676.   SKIP_SOMETHING (cursor, keyafter.end);
  1677.   key.end = cursor;
  1678.   after.start = cursor;
  1679.   print_field (key);
  1680.   printf ("}{");
  1681.   print_field (after);
  1682.   printf ("}{");
  1683.   print_field (head);
  1684.   printf ("}");
  1685.   if (auto_reference || input_reference)
  1686.     {
  1687.       printf ("{");
  1688.       print_field (reference);
  1689.       printf ("}");
  1690.     }
  1691.   printf ("\n");
  1692. }
  1693.  
  1694.  
  1695. /* Output the current output fields as one line for a dumb terminal.  */
  1696.  
  1697. void
  1698. #ifndef __STDC__
  1699. output_one_dumb_line ()
  1700. #else
  1701. output_one_dumb_line (void)
  1702. #endif
  1703. {
  1704.   if (!right_reference)
  1705.     if (auto_reference)
  1706.       {
  1707.  
  1708.         /* Output the `reference' field, in such a way that GNU emacs
  1709.            next-error will handle it.  The ending colon is taken from the
  1710.            gap which follows.  */
  1711.  
  1712.     print_field (reference);
  1713.     putchar (':');
  1714.     print_spaces (reference_max_width
  1715.               + gap_size
  1716.               - (reference.end - reference.start)
  1717.               - 1);
  1718.       }
  1719.     else
  1720.       {
  1721.  
  1722.     /* Output the `reference' field and its following gap.  */
  1723.  
  1724.     print_field (reference);
  1725.     print_spaces (reference_max_width
  1726.             + gap_size
  1727.             - (reference.end - reference.start));
  1728.       }
  1729.  
  1730.   if (tail.start < tail.end)
  1731.     {
  1732.       /* Output the `tail' field.  */
  1733.  
  1734.       print_field (tail);
  1735.       if (tail_truncation)
  1736.     printf ("%s", truncation_string);
  1737.  
  1738.       print_spaces (half_line_width - gap_size
  1739.             - (before.end - before.start)
  1740.             - (before_truncation ? truncation_string_length : 0)
  1741.             - (tail.end - tail.start)
  1742.             - (tail_truncation ? truncation_string_length : 0));
  1743.     }
  1744.   else
  1745.     print_spaces (half_line_width - gap_size
  1746.           - (before.end - before.start)
  1747.           - (before_truncation ? truncation_string_length : 0));
  1748.  
  1749.   /* Output the `before' field.  */
  1750.  
  1751.   if (before_truncation)
  1752.     printf ("%s", truncation_string);
  1753.   print_field (before);
  1754.  
  1755.   print_spaces (gap_size);
  1756.  
  1757.   /* Output the `keyafter' field.  */
  1758.  
  1759.   print_field (keyafter);
  1760.   if (keyafter_truncation)
  1761.     printf ("%s", truncation_string);
  1762.  
  1763.   if (head.start < head.end)
  1764.     {
  1765.       /* Output the `head' field.  */
  1766.  
  1767.       print_spaces (half_line_width
  1768.             - (keyafter.end - keyafter.start)
  1769.             - (keyafter_truncation ? truncation_string_length : 0)
  1770.             - (head.end - head.start)
  1771.             - (head_truncation ? truncation_string_length : 0));
  1772.       if (head_truncation)
  1773.     printf ("%s", truncation_string);
  1774.       print_field (head);
  1775.     }
  1776.   else
  1777.  
  1778.     if ((auto_reference || input_reference) && right_reference)
  1779.       print_spaces (half_line_width
  1780.             - (keyafter.end - keyafter.start)
  1781.             - (keyafter_truncation ? truncation_string_length : 0));
  1782.  
  1783.   if ((auto_reference || input_reference) && right_reference)
  1784.     {
  1785.       /* Output the `reference' field.  */
  1786.  
  1787.       print_spaces (gap_size);
  1788.       print_field (reference);
  1789.     }
  1790.  
  1791.   printf ("\n");
  1792. }
  1793.  
  1794.  
  1795. /* Scan the whole occurs table and, for each entry, output one line in the
  1796.    appropriate format.  */
  1797.  
  1798. void
  1799. #ifndef __STDC__
  1800. generate_all_output ()
  1801. #else
  1802. generate_all_output (void)
  1803. #endif
  1804. {
  1805.   int occurs_index;        /* index of keyword entry being processed */
  1806.   OCCURS *occurs_cursor;    /* current keyword entry being processed */
  1807.  
  1808.  
  1809.   /* The following assignments are useful to provide default values in case
  1810.      line contexts or references are not used, in which case these variables
  1811.      would never be computed.  */
  1812.  
  1813.   tail.start = NULL;
  1814.   tail.end = NULL;
  1815.   tail_truncation = 0;
  1816.  
  1817.   head.start = NULL;
  1818.   head.end = NULL;
  1819.   head_truncation = 0;
  1820.  
  1821.  
  1822.   /* Loop over all keyword occurrences.  */
  1823.  
  1824.   occurs_cursor = occurs_table[0];
  1825.  
  1826.   for (occurs_index = 0; occurs_index < number_of_occurs[0]; occurs_index++)
  1827.     {
  1828.       /* Compute the exact size of every field and whenever truncation flags
  1829.      are present or not.  */
  1830.  
  1831.       define_all_fields (occurs_cursor);
  1832.  
  1833.       /* Produce one output line according to selected format.  */
  1834.  
  1835.       switch (output_format)
  1836.     {
  1837.     case UNKNOWN_FORMAT:
  1838.       /* Should never happen.  */
  1839.  
  1840.     case DUMB_FORMAT:
  1841.       output_one_dumb_line ();
  1842.       break;
  1843.  
  1844.     case ROFF_FORMAT:
  1845.       output_one_roff_line ();
  1846.       break;
  1847.  
  1848.     case TEX_FORMAT:
  1849.       output_one_tex_line ();
  1850.       break;
  1851.     }
  1852.  
  1853.       /* Advance the cursor into the occurs table.  */
  1854.  
  1855.       occurs_cursor = (OCCURS *) ((char *) occurs_cursor + sizeof_occurs);
  1856.     }
  1857. }
  1858.  
  1859. /* Option decoding and main program.  */
  1860.  
  1861. #ifndef PTX_COMPATIBILITY
  1862.  
  1863. /* Long options equivalences.  */
  1864.  
  1865. struct option longopts[] =
  1866. {
  1867.   {"copyright", 0, NULL, 'C'},
  1868.   {"break"    , 1, NULL, 'b'},
  1869.   {"foldcase" , 0, NULL, 'f'},
  1870.   {"gapsize"  , 1, NULL, 'g'},
  1871.   {"ignore"   , 1, NULL, 'i'},
  1872.   {"only"     , 1, NULL, 'o'},
  1873.   {"reference", 0, NULL, 'r'},
  1874.   {"typeset"  , 0, NULL, 't'},
  1875.   {"width"    , 1, NULL, 'w'},
  1876.   {"autorefer", 0, NULL, 'A'},
  1877.   {"flagtrunc", 1, NULL, 'F'},
  1878.   {"runoff"   , 0, NULL, 'O'},
  1879.   {"rightside", 0, NULL, 'R'},
  1880.   {"sentence" , 1, NULL, 'S'},
  1881.   {"tex"      , 0, NULL, 'T'},
  1882.   {"word"     , 1, NULL, 'W'},
  1883.   {NULL       , 0, NULL, 0}
  1884. };
  1885. #endif
  1886.  
  1887.  
  1888. /* Print program identification and options, then exit.  */
  1889.  
  1890. void
  1891. #ifndef __STDC__
  1892. usage_and_exit ()
  1893. #else
  1894. usage_and_exit (void)
  1895. #endif
  1896. {
  1897.   print_version ();
  1898.  
  1899. #ifdef PTX_COMPATIBILITY
  1900.  
  1901.   fprintf (stderr, "usage: %s [OPTION]... [INPUT [OUTPUT]]\n",
  1902.        program_name);
  1903.  
  1904.   fprintf (stderr, "\
  1905. \n\
  1906.   -C        display Copyright and copying conditions, then exit\n\
  1907.   -b FILE    word break characters in this FILE\n\
  1908.   -f        fold lower case to upper case for sorting\n\
  1909.   -g NUMBER    gap size in characters between output fields\n\
  1910.   -i FILE    read ignore word list from FILE\n\
  1911.   -o FILE    read only word list from this FILE\n\
  1912.   -r        first field of each line is a reference\n\
  1913.   -t        - still unimplemented -\n\
  1914.   -w NUMBER    output line width in characters, reference excluded\n");
  1915.  
  1916. #else /* not PTX_COMPATIBILITY */
  1917.  
  1918.   fprintf (stderr, "usage: %s [OPTION]... [INPUT]...\n",
  1919.        program_name);
  1920.  
  1921.   fprintf (stderr, "\
  1922. \n\
  1923.   -C, +copyright    display Copyright and copying conditions, then exit\n\
  1924.   -b, +break FILE    word break characters in this FILE\n\
  1925.   -f, +foldcase        fold lower case to upper case for sorting\n\
  1926.   -g, +gapsize NUMBER    gap size in characters between output fields\n\
  1927.   -i, +ignore FILE    read ignore word list from FILE\n\
  1928.   -o, +only FILE    read only word list from this FILE\n\
  1929.   -r, +reference    first field of each line is a reference\n\
  1930.   -t, +typeset        - still unimplemented -\n\
  1931.   -w, +width NUMBER    output line width in characters, reference excluded\n\
  1932.   -A, +autorefer    output automatically generated references\n\
  1933.   -F, +flagtrunc STRING    flag line truncations with STRING (default is `/')\n\
  1934.   -O, +runoff        generate output as roff directives\n\
  1935.   -R, +rightside    references after right context, not counted in -w\n\
  1936.   -S, +sentence REGEXP    use REGEXP to match end of lines or end of sentences\n\
  1937.   -T, +tex        generate output as TeX directives\n\
  1938.   -W, +word REGEXP    use REGEXP to match each keyword\n");
  1939.  
  1940. #endif /* not PTX_COMPATIBILITY */
  1941.  
  1942.   exit (-1);
  1943. }
  1944.  
  1945.  
  1946. /* Main program.  Decode ARGC arguments passed through the ARGV array of
  1947.    strings, then launch execution.  */
  1948.  
  1949. void
  1950. #ifndef __STDC__
  1951. main (argc, argv)
  1952.      int argc;
  1953.      char *argv[];
  1954. #else
  1955. main (int argc, const char *argv[])
  1956. #endif
  1957. {
  1958.   int optchar;            /* argument character */
  1959. #ifdef PTX_COMPATIBILITY
  1960.   extern int optind;        /* index of argument */
  1961.   extern char *optarg;        /* value or argument */
  1962. #endif
  1963.   int file_index;        /* index in text input file arrays */
  1964.  
  1965. #ifndef MCHECK_MISSING
  1966.   /* Use gmalloc checking.  It has proven to be useful!  */
  1967.  
  1968.   extern void mcheck ();
  1969.   mcheck ();
  1970. #endif /* not MCHECK_MISSING */
  1971.  
  1972.   /* Decode program options.  */
  1973.  
  1974.   program_name = argv[0];
  1975.   
  1976.   while ((optchar
  1977. #ifdef PTX_COMPATIBILITY
  1978.       = getopt (argc, argv, GETOPT_STRING)
  1979. #else
  1980.       = getopt_long (argc, (char **) argv,
  1981.              GETOPT_STRING, longopts, (int *) 0)
  1982. #endif
  1983.       ) != EOF)
  1984.     {
  1985.       switch (optchar)
  1986.     {
  1987.     case 'C':
  1988.       print_version ();
  1989.       print_copyright ();
  1990.       exit (0);
  1991.  
  1992.     case 'b':
  1993.       break_file = optarg;
  1994.       break;
  1995.  
  1996.     case 'f':
  1997.       fold_lower_to_upper = 1;
  1998.       break;
  1999.  
  2000.     case 'g':
  2001.       gap_size = atoi (optarg);
  2002.       break;
  2003.  
  2004.     case 'i':
  2005.       ignore_file = optarg;
  2006.       break;
  2007.  
  2008.     case 'o':
  2009.       only_file = optarg;
  2010.       break;
  2011.  
  2012.     case 'r':
  2013.       input_reference = 1;
  2014.       break;
  2015.  
  2016.     case 't':
  2017.       /* A decouvrir...  */
  2018.       break;
  2019.  
  2020.     case 'w':
  2021.       line_width = atoi (optarg);
  2022.       break;
  2023.  
  2024. #ifndef PTX_COMPATIBILITY
  2025.  
  2026.     case 'A':
  2027.       auto_reference = 1;
  2028.       break;
  2029.  
  2030.     case 'F':
  2031.       truncation_string = optarg;
  2032.       break;
  2033.  
  2034.     case 'O':
  2035.       output_format = ROFF_FORMAT;
  2036.       break;
  2037.  
  2038.     case 'R':
  2039.       right_reference = 1;
  2040.       break;
  2041.  
  2042.     case 'S':
  2043.       context_regex_string = optarg;
  2044.       break;
  2045.  
  2046.     case 'T':
  2047.       output_format = TEX_FORMAT;
  2048.       break;
  2049.  
  2050.     case 'W':
  2051.       word_regex_string = optarg;
  2052.       break;
  2053.  
  2054. #endif /* not PTX_COMPATIBILITY */
  2055.  
  2056.     default:
  2057.       usage_and_exit ();
  2058.     }
  2059.     }
  2060.  
  2061. #ifdef DEFAULT_IGNORE_FILE
  2062.  
  2063.   /* Change the default Ignore file if one is defined.  */
  2064.  
  2065.   if (!ignore_file)
  2066.     {
  2067.       ignore_file = DEFAULT_IGNORE_FILE;
  2068.     }
  2069.  
  2070. #endif /* IGNORE */
  2071.  
  2072.   /* Process remaining arguments.  If ptx compatibility is enabled, accept
  2073.      at most two arguments, the second of which is an output parameter.
  2074.      If disabled, process all arguments as input parameters.  */
  2075.  
  2076.   if (optind == argc)
  2077.     {
  2078.  
  2079.       /* No more argument simply means: read standard input.  */
  2080.  
  2081.       input_file_name = (const char **) xmalloc (sizeof (const char *));
  2082.       file_line_count = (int *) xmalloc (sizeof (int));
  2083.       number_input_files = 1;
  2084.       input_file_name[0] = NULL;
  2085.     }
  2086.   else
  2087.     {
  2088.  
  2089. #ifdef PTX_COMPATIBILITY
  2090.  
  2091.       /* There is one necessary input file.  */
  2092.  
  2093.       number_input_files = 1;
  2094.       input_file_name = (const char **) xmalloc (sizeof (const char *));
  2095.       file_line_count = (int *) xmalloc (sizeof (int));
  2096.       input_file_name[0] = argv[optind];
  2097.       if (!*argv[optind] || strcmp (argv[optind], "-") == 0)
  2098.     input_file_name[0] = NULL;
  2099.       else
  2100.     input_file_name[0] = argv[optind];
  2101.       optind++;
  2102.  
  2103.       /* Redirect standard output, only if requested.  */
  2104.  
  2105.       if (optind < argc)
  2106.     {
  2107.       fclose (stdout);
  2108.       if (fopen (argv[optind], "w") == NULL)
  2109.         perror_and_exit (argv[optind]);
  2110.       optind++;
  2111.     }
  2112.  
  2113.       /* Diagnose any other argument as an error.  */
  2114.  
  2115.       if (optind < argc)
  2116.     usage_and_exit ();
  2117.  
  2118. #else /* not PTX_COMPATIBILITY */
  2119.  
  2120.       number_input_files = argc - optind;
  2121.       input_file_name
  2122.     = (const char **) xmalloc (number_input_files * sizeof (const char *));
  2123.       file_line_count
  2124.     = (int *) xmalloc (number_input_files * sizeof (int));
  2125.  
  2126.       for (file_index = 0; file_index < number_input_files; file_index++)
  2127.     {
  2128.       input_file_name[file_index] = argv[optind];
  2129.       if (!*argv[optind] || strcmp (argv[optind], "-") == 0)
  2130.         input_file_name[0] = NULL;
  2131.       else
  2132.         input_file_name[0] = argv[optind];
  2133.       optind++;
  2134.     }
  2135.  
  2136. #endif /* not PTX_COMPATIBILITY */
  2137.  
  2138.     }
  2139.  
  2140.   /* If the output format has not been explicitely selected, choose
  2141.      `roff' format if ptx compatibility is enabled, else choose dumb
  2142.      terminal format.  */
  2143.  
  2144.   if (output_format == UNKNOWN_FORMAT)
  2145.     {
  2146. #ifdef PTX_COMPATIBILITY
  2147.     output_format = ROFF_FORMAT;
  2148. #else
  2149.     output_format = DUMB_FORMAT;
  2150. #endif
  2151.     }
  2152.  
  2153.   /* Initialize the main tables.  */
  2154.  
  2155.   initialize_regex ();
  2156.  
  2157.   sizeof_occurs = sizeof (OCCURS);
  2158. #if 0                /* Le mieux est l'ennemi du bien! */
  2159.   if (!auto_reference)
  2160.     {
  2161.       sizeof_occurs -= sizeof (int);
  2162.       if (input_reference)
  2163.     sizeof_occurs += sizeof (DELTA);
  2164.     }
  2165. #endif
  2166. #ifdef OCCURS_ALIGNMENT
  2167.   sizeof_occurs = ((sizeof_occurs + OCCURS_ALIGNMENT - 1)
  2168.            & ~(OCCURS_ALIGNMENT - 1));
  2169. #endif
  2170.  
  2171.   /* Read `Break character' file, if any.  */
  2172.  
  2173.   if (break_file)
  2174.     digest_break_file (break_file);
  2175.  
  2176.   /* Read `Ignore words' file and `Only words' files, if any.  If any of
  2177.      these files is empty, reset the name of the file to NULL, to avoid
  2178.      unnecessary calls to search_table. */
  2179.  
  2180.   if (ignore_file)
  2181.     {
  2182.       digest_word_file (ignore_file, &ignore_table);
  2183.       if (ignore_table.length == 0)
  2184.     ignore_file = NULL;
  2185.     }
  2186.  
  2187.   if (only_file)
  2188.     {
  2189.       digest_word_file (only_file, &only_table);
  2190.       if (only_table.length == 0)
  2191.     only_file = NULL;
  2192.     }
  2193.  
  2194.   /* Prepare to study all the input files.  */
  2195.  
  2196.   number_of_occurs[0] = 0;
  2197.   total_line_count = 0;
  2198.   maximum_word_length = 0;
  2199.   reference_max_width = 0;
  2200.  
  2201.   for (file_index = 0; file_index < number_input_files; file_index++)
  2202.     {
  2203.  
  2204.       /* Read the file in core, than study it.  */
  2205.  
  2206.       swallow_file_in_memory (input_file_name[file_index], &text_buffer);
  2207.       find_occurs_in_text ();
  2208.  
  2209.       /* Maintain for each file how many lines has been read so far when its
  2210.      end is reached.  Incrementing the count first is a simple kludge to
  2211.      handle a possible incomplete line at end of file.  */
  2212.  
  2213.       total_line_count++;
  2214.       file_line_count[file_index] = total_line_count;
  2215.     }
  2216.  
  2217.   /* Do the output process phase.  */
  2218.  
  2219.   sort_found_occurs ();
  2220.   fix_output_parameters ();
  2221.   generate_all_output ();
  2222.  
  2223.   /* All done.  */
  2224.  
  2225.   exit (0);
  2226. }
  2227.